package hlhj.fhp.supreme.activitys

import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.support.annotation.RequiresApi
import android.view.View
import android.webkit.*
import android.widget.ProgressBar
import hlhj.fhp.supreme.BaseAty
import hlhj.fhp.supreme.R
import hlhj.fhp.supreme.customview.MyChromeClient
import hlhj.fhp.supreme.js.JiePanJs
import hlhj.fhp.supreme.toast
import kotlinx.android.synthetic.main.articleedit_aty.*
import hlhj.fhp.supreme.customview.MyChromeClient.FILECHOOSER_RESULTCODE
import android.support.v4.app.ActivityCompat.startActivityForResult
import android.widget.Toast
import fhp.hlhj.giantfold.utils.ToastUtils
import hlhj.fhp.supreme.customview.MyChromeClient.FILECHOOSER_RESULTCODE
import android.support.v4.app.ActivityCompat.startActivityForResult
import android.util.Log
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMGroupManager
import com.hyphenate.chat.EMGroupOptions
import com.lzy.okgo.OkGo
import com.lzy.okgo.model.Response
import fhp.hlhj.giantfold.utils.LogUtil
import hlhj.fhp.supreme.javabean.BaseBean
import hlhj.fhp.supreme.javabean.CommitBean
import hlhj.fhp.supreme.javabean.JiePanCommitEvent
import hlhj.fhp.supreme.network.Urls
import hlhj.fhp.supreme.utils.JsonCallBack
import hlhj.fhp.supreme.utils.MyUtils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode


/**
 * Created by Never Fear   on 2018\7\18 0018.
Never More....
 */
class ArticleEditAty:BaseAty() {
    private var id:String?=null
    val REQUEST_SELECT_FILE = 100
    val FILECHOOSER_RESULTCODE = 1
    var isSave=false
    var uploadMessage: ValueCallback<Array<Uri>>?=null
    var mUploadMessage: ValueCallback<Uri>?=null
//    lateinit  var mWebLoadingProgressBar: ProgressBar

    override fun getContentId(): Int {
        return R.layout.articleedit_aty
    }

    @SuppressLint("SetJavaScriptEnabled")
    override fun initView() {
        btExit.setOnClickListener {
            finish()
        }
        if (intent.getStringExtra("id")==null){
            id=null
        }else{
            id=intent.getStringExtra("id")
        }

        EventBus.getDefault().register(this)


        initWeb()
    }

    @RequiresApi(Build.VERSION_CODES.KITKAT)
    override fun initListener() {
        btCommit.setOnClickListener {
            webView.evaluateJavascript("javascript:getEl()",object :ValueCallback<String>{
                override fun onReceiveValue(value: String?) {
                    val temp1 = value?.replace("\\u003C", "<")
                    val temp2 = temp1?.substring(1,temp1.length-1)

                    Log.e("fhppp","获取的富文本为${value}")

                }
            })
        }

    }
    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    private fun initWeb() {
        webView.webViewClient = object : WebViewClient() {
        }
        webView.webChromeClient=SafeWebViewClient(this@ArticleEditAty)
        webView.settings.javaScriptEnabled = true
        webView.requestFocusFromTouch();
        val webSettings = webView.settings
        webSettings.allowFileAccess = true
        webSettings .setSupportZoom(false);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
//调整图片至适合webview的大小
//        webSettings .setUseWideViewPort(true);
// 缩放至屏幕的大小
        webSettings .setLoadWithOverviewMode(true);
//设置默认编码
        webSettings .setDefaultTextEncodingName("utf-8");
////设置自动加载图片
        webSettings .setLoadsImagesAutomatically(true);
        webSettings.domStorageEnabled=true
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        //提高渲染的优先级
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webView.addJavascriptInterface(JiePanJs(id,this@ArticleEditAty),"Obj")
//        webView.loadDataWithBaseURL(null, "https://eleditor.fixel.cn/demo.html","text/html", "utf-8", null)
//        webView.loadUrl("file:///android_asset/Eleditor-master/demo/index.html")
        Thread(Runnable {
            Thread.sleep(10)
            runOnUiThread {
                        webView.loadUrl("file:///android_asset/Eleditor-master/demo/index.html")
            }
        }).start()
    }
    @Subscribe(threadMode = ThreadMode.POSTING)
    fun getHtml(event:JiePanCommitEvent){
        Log.e("fhppp","eventBus传来的值${event.htmlStr}")
        if (event.htmlStr.equals("<p class=\"Eleditor-placeholder\">内容编辑区</p>")){
            MyUtils.toast("请先点击编辑框下方的提交按钮保存文本内容")
        }else{
            if (id==null){
                OkGo.post<CommitBean>(Urls.BaseUrl+Urls.ADD_ARTICLE)
                        .params("cat_id",intent.getStringExtra("cid"))
                        .params("title",intent.getStringExtra("tittle"))
                        .params("content",event.htmlStr)
                        .params("des",intent.getStringExtra("des"))
                        .execute(object :JsonCallBack<CommitBean>(this@ArticleEditAty){
                            override fun onSuccess(response: Response<CommitBean>?) {
                                val baseBean = response?.body()!!
                                if (baseBean.code==1){
                                    Thread(Runnable {
                                        val option = EMGroupOptions()
                                        option.maxUsers = 2000
                                        option.style = EMGroupManager.EMGroupStyle.EMGroupStylePublicOpenJoin
                                        option.inviteNeedConfirm=false
                                        val strings = arrayOfNulls<String>(0)
                                        val group = EMClient.getInstance().groupManager().createGroup(intent.getStringExtra("tittle")
                                                , intent.getStringExtra("des"),
                                                strings, null, option)
                                        if (group!=null){
                                            Log.e("fhppp","传入的Id${group.groupId}")
                                            OkGo.post<BaseBean>(Urls.BaseUrl+Urls.CREATE_ROOM)
                                                    .params("id",group.groupId)
                                                    .params("breakup_id",baseBean.data.id)
                                                    .execute(object :JsonCallBack<BaseBean>(this@ArticleEditAty){
                                                        override fun onSuccess(response: Response<BaseBean>?) {
                                                            val bean = response?.body()
                                                            if (bean?.code==1){
                                                                MyUtils.toast("解盘开始！")
                                                                val intent = Intent(this@ArticleEditAty, JiePanDetailAty::class.java)
                                                                intent.putExtra("roomId",group.groupId)
                                                                startActivity(intent)
                                                            }else{
                                                                MyUtils.toast(bean?.msg)
                                                            }
                                                            finish()
                                                        }
                                                    })
                                        }
                                        LogUtil.logi(group.isMemberOnly.toString())
                                    }).start()
                                }else{
                                    this.toast(this@ArticleEditAty,baseBean.msg)
                                }
                            }
                        })
            }else{
                MyUtils.toast("得到的cid${intent.getIntExtra("cid",0)}")
                OkGo.post<BaseBean>(Urls.BaseUrl+Urls.EDIT_ART)
                        .params("id",intent.getStringExtra("id"))
                        .params("des",intent.getStringExtra("des"))
                        .params("cat_id",intent.getIntExtra("cid",0))
                        .params("title",intent.getStringExtra("title"))
                        .params("content",event.htmlStr)
                        .execute(object :JsonCallBack<BaseBean>(this@ArticleEditAty){
                            override fun onSuccess(response: Response<BaseBean>?) {
                                val baseBean = response?.body()!!
                                if (baseBean.code==1){
                                    MyUtils.toast("修改成功")
                                    finish()
                                }else{
                                    MyUtils.toast(baseBean.msg)
                                }
                            }
                        })
            }
        }

    }

    @SuppressLint("NewApi")
    public override fun onActivityResult(requestCode: Int, resultCode: Int, intent: Intent?) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (null == mUploadMessage) return
            val result = if (intent == null || resultCode != Activity.RESULT_OK) null else intent.data
            mUploadMessage!!.onReceiveValue(result)
            mUploadMessage = null
        } else if (requestCode == REQUEST_SELECT_FILE) {
            if (uploadMessage == null) return
            uploadMessage!!.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent))
            uploadMessage = null
        }
    }
}

class SafeWebViewClient(private val activity: ArticleEditAty) : WebChromeClient() {
    override fun onProgressChanged(view: WebView, newProgress: Int) {
        super.onProgressChanged(view, newProgress)
      /*  activity.mWebLoadingProgressBar.setProgress(newProgress)
        if (newProgress >= 90 && activity.mWebLoadingProgressBar.getVisibility() === View.VISIBLE) {
            activity.mWebLoadingProgressBar.setVisibility(View.GONE)
        }*/
    }

    //The undocumented magic method override
    //Eclipse will swear at you if you try to put @Override here
    // For Android 3.0+
    fun openFileChooser(uploadMsg: ValueCallback<Uri>) {

        activity.mUploadMessage = uploadMsg
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), activity.FILECHOOSER_RESULTCODE)

    }

    // For Android 3.0+
    @SuppressWarnings("static-access")
    fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String) {
        activity.mUploadMessage = uploadMsg
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "*/*"
        activity.startActivityForResult(Intent.createChooser(i, "File Browser"), activity.FILECHOOSER_RESULTCODE)
    }

    //For Android 4.1
    fun openFileChooser(uploadMsg: ValueCallback<Uri>, acceptType: String, capture: String) {
        activity.mUploadMessage = uploadMsg
        val i = Intent(Intent.ACTION_GET_CONTENT)
        i.addCategory(Intent.CATEGORY_OPENABLE)
        i.type = "image/*"
        activity.startActivityForResult(Intent.createChooser(i, "File Chooser"), activity.FILECHOOSER_RESULTCODE)

    }

    //For Android 5.0
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    override fun onShowFileChooser(webView: WebView, filePathCallback: ValueCallback<Array<Uri>>, fileChooserParams: WebChromeClient.FileChooserParams): Boolean {
//        ToastUtils.toast(activity,"111")
        // make sure there is no existing message
        if (activity.uploadMessage != null) {
            activity!!.uploadMessage!!.onReceiveValue(null)
            activity.uploadMessage = null
        }
        activity.uploadMessage = filePathCallback
        /*val intent = fileChooserParams.createIntent()

        try {
            activity.startActivityForResult(intent, activity.REQUEST_SELECT_FILE)
        } catch (e: ActivityNotFoundException) {
            activity.uploadMessage = null
            return false
        }*/

        val i = Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        activity.startActivityForResult(i, activity.REQUEST_SELECT_FILE)
        return true
    }

}